<?php

namespace juliang\api;

use juliang\utils\HttpKit;
use juliang\utils\ResponseKit;
use juliang\utils\SignKit;

class CompanyDynamic
{
    // 业务编号
    private string $trade_no;
    // 业务密钥
    private string $key;
    // 提取数量
    private int $num;

    /**
     * 提取动态IP
     */
    public CONST GET_IPS_ACTION = "COMPANY_DYNAMIC_GET_IPS";

    /**
     * 设置IP白名单
     */
    public CONST SET_WHITE_IP_ACTION = "COMPANY_DYNAMIC_SET_WHITE_IP";

    /**
     * 获取IP白名单
     */
    public CONST GET_WHITE_IP_ACTION = "COMPANY_DYNAMIC_GET_WHITE_IP";

    /**
     * 替换IP白名单
     */
    public CONST DEL_WHITE_IP_ACTION = "COMPANY_DYNAMIC_DEL_WHITE_IP";

    /**
     * 获取动态代理信息初始化
     * @param string $trade_no
     * @param int $num
     * @param string $key
     */
    public function __construct(string $trade_no, int $num, string $key)
    {
        $this->trade_no = $trade_no;
        $this->num = $num;
        $this->key = $key;
    }

    /**
     * 执行操作
     * @param string $action
     * @param array $params
     * @param string $requestMethod
     * @return mixed|void
     */
    public function action(string $action, array $params = [], string $requestMethod = "GET")
    {
        // 获取对应Api
        $apiUrl = Common::getApiUrl($action);
        if (empty($apiUrl)) {
            ResponseKit::apiReturn(['code' => 400, 'msg' => "暂不支持此操作，请参照代码示例修改"]);
        }
        $params['trade_no'] = $this->trade_no;
        if ($action === self::GET_IPS_ACTION) {
            $params['num']  = $this->num;
        }
        $params['sign'] = SignKit::md5Sign($params, $this->key);
        $getIpsResult = HttpKit::sendRequest($apiUrl, $params, $requestMethod);
        if (true === $getIpsResult['ret']) {
            return $getIpsResult['data'];
        }
        ResponseKit::apiReturn(['code' => 400, 'msg' => $getIpsResult['msg']]);
    }
}